<!-- src/components/VideoPlayer.vue -->
<template>
    <div class="video-player">
        <video ref="videoRef" @error="handleVideoError" class="live-video" @click="handleUserAction"
            @fullscreenchange="handleFullscreenChange">
            <source :src="currentSrc" type="application/x-mpegURL" />
            您的浏览器不支持 HTML5 视频标签。
        </video>
        <div class="custom-controls" v-if="!isControlsHidden">
            <!-- 播放/暂停按钮 -->
            <i :class="isPlaying ? 'iconfont icon-zanting' : 'iconfont icon-bofang'" @click="togglePlayPause"></i>
            <!-- 刷新按钮 -->
            <i :class="['iconfont', 'icon-shuaxin', { 'refresh-spin': isRefreshing }]" @click="refreshVideo"></i>
            <!-- 弹幕按钮 -->
            <i :class="danmuStore.isDanmuVisible ? 'iconfont icon-danmushezhi' : 'iconfont icon-guanbidanmu'"
                @click="toggleDanmu"></i>
            <!-- 视频画质选择 -->
            <select class="quality-select" v-model="selectedQuality" @change="changeQuality">
                <option v-for="(quality, index) in qualities" :key="index" :value="quality.src">
                    {{ quality.label }}
                </option>
            </select>
            <!-- 全屏按钮 -->
            <i class="iconfont icon-quanping" @click="toggleFullscreen"></i>
            <!-- 音量按钮 -->
            <div class="volume-container">
                <div class="volume-control" v-if="showVolumeControl">
                    <input type="range" min="0" max="100" v-model="volume" @input="setVolume" />
                </div>
                <i :class="isMuted ? 'iconfont icon-24gf-volumeDisable' : 'iconfont icon-24gf-volumeMiddle'"
                    @click="toggleVolume" @mouseover="showVolumeControl = true"
                    @mouseleave="showVolumeControl = false"></i>
            </div>
        </div>
    </div>
</template>

<script setup>
import { throttle } from 'lodash'
import { useDanmuStore } from '../../stores/danmu/danmu'
import { ref, onMounted, onUnmounted, watch } from 'vue';
import Hls from 'hls.js';
import { ElMessage } from 'element-plus';
const props = defineProps({
    sources: {
        type: Array,
        required: true,
        default: () => [
            { label: '高清', src: 'https://example.com/high.m3u8' },
            { label: '标清', src: 'https://example.com/standard.m3u8' },
            { label: '流畅', src: 'https://example.com/low.m3u8' }
        ]
    },
    chatMessages: {
        type: Array,
        required: true,
        default: () => []
    },
    qualities: {
        type: Array,
        required: true,
        default: () => [
            { label: '原画', src: 'https://cn-jsyz-ct-03-31.bilivideo.com/live-bvc/952695/live_773977_8790152_bluray/index.m3u8?expires=1735572093&len=0&oi=993562372&pt=web&qn=10000&trid=100718e6762df2006fef64178d461a67772ac&sigparams=cdn,expires,len,oi,pt,qn,trid&cdn=cn-gotcha01&sign=14dfdcef810a11576963e985aaa6507b&site=4618b9ffd4a24657b314794ea1642f2e&free_type=0&mid=434049513&sche=ban&bvchls=1&sid=cn-jsyz-ct-03-31&chash=1&bmt=1&sg=lr&trace=25&isp=ct&rg=East&pv=Fujian&hot_cdn=57417&source=puv3_onetier&flvsk=1304f646dfeb4df8b6e7ff33c167d3ad87b2a035213a12b2efcdf778dee61a04&deploy_env=prod&suffix=bluray&origin_bitrate=1021182&sl=3&p2p_type=1&qp=hv_10000&sk=657866af8fc16d8b2b84dfdde3e98143e94acb5d1a3a50bd0d253c50ef412f31&pp=rtmp&score=1&info_source=cache&vd=nc&zoneid_l=151371777&sid_l=stream_name_cold&src=puv3&order=1' },
            { label: '高清', src: 'https://cn-jsyz-ct-03-73.bilivideo.com/live-bvc/212595/live_773977_8790152_2500/index.m3u8?expires=1735574376&len=0&oi=993562372&pt=web&qn=250&trid=100740d9fa8fb8389baf4ad5550fef6772b5&sigparams=cdn,expires,len,oi,pt,qn,trid&cdn=cn-gotcha01&sign=6e5ecbcd7f73d22d153ba5a834bede18&site=99e73c3dd5b1eea9f5e5b9976b1ec174&free_type=0&mid=434049513&sche=ban&bvchls=1&sid=cn-jsyz-ct-03-73&chash=1&bmt=1&sg=lr&trace=8388633&isp=ct&rg=East&pv=Fujian&origin_bitrate=1022488&p2p_type=1&hot_cdn=57417&pp=rtmp&sk=657866af8fc16d8b2b84dfdde3e98143e94acb5d1a3a50bd0d253c50ef412f31&deploy_env=prod&suffix=2500&source=puv3_onetier&score=1&sl=3&flvsk=1304f646dfeb4df8b6e7ff33c167d3ad87b2a035213a12b2efcdf778dee61a04&info_source=cache&vd=nc&zoneid_l=151371777&sid_l=stream_name_cold&src=puv3&order=1' }
        ]
    }
});
//音量控制
const showVolumeControl = ref(false);  // 控制音量条显示与否
const volume = ref(50);
const isMuted = ref(false);
const toggleVolume = () => {
    if (videoRef.value) {
        videoRef.value.muted = !videoRef.value.muted
        volume.value = videoRef.value.muted ? 0 : 50;
        // 如果静音则设置音量为0，否则设置为50
    }
    isMuted.value = !isMuted.value;
}
const setVolume = (event) => {
    if (videoRef.value) {
        videoRef.value.volume = volume.value / 100;  // 音量值应在 0 到 1 之间
        if (volume.value === 0) {
            videoRef.value.muted = true;  // 如果音量为 0，则静音
            isMuted.value = true;
        } else {
            videoRef.value.muted = false;  // 如果音量大于 0，则取消静音
            isMuted.value = false;
        }
    }
}
//实例化弹幕显示状态
const danmuStore = useDanmuStore();
const emit = defineEmits(['sendMessage', 'toggleDanmu']);
const isPlaying = ref(false);// 新增状态变量
const currentSrc = ref(props.sources[0].src);
const selectedQuality = ref(props.sources[0].src);
const newMessage = ref('');
const videoRef = ref(null);
// 新增状态变量
const isRefreshing = ref(false);
// 新增状态变量
const isControlsHidden = ref(false);
// 新增定时器变量
const inactivityTimer = ref(null);
let hls = null;
const toggleDanmu = () => {
    // 切换弹幕显示状态
    danmuStore.toggleDanmuVisible();
    emit('toggleDanmu', danmuStore.isDanmuVisible);
}
//进入全屏时，隐藏控制栏
const handleFullscreenChange = () => {
    if (document.fullscreenElement || document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement) {
        // 进入全屏模式，显示控件
        isControlsHidden.value = false;
        clearTimeout(inactivityTimer.value);
    } else {
        // 退出全屏模式，重置控件隐藏逻辑
        inactivityTimer.value = setTimeout(() => {
            isControlsHidden.value = true;
        }, 5000);
    }
}
//全屏控制
const toggleFullscreen = () => {
    if (videoRef.value) {
        if (videoRef.value.requestFullscreen) {
            videoRef.value.requestFullscreen();
        } else if (videoRef.value.webkitRequestFullscreen) {
            //chrome, safari等webkit内核浏览器
            videoRef.value.webkitRequestFullscreen();
        } else if (videoRef.value.mozRequestFullScreen) {
            //火狐浏览器
            videoRef.value.mozRequestFullScreen();
        } else if (videoRef.value.msRequestFullscreen) {
            //IE浏览器
            videoRef.value.msRequestFullscreen();
        }
    }
}
// UI界面隐藏控制
const handleUserAction = (event) => {
    // 切换控件的显示和隐藏状态
    isControlsHidden.value = !isControlsHidden.value;
    // 如果控件显示，则重置定时器
    if (!isControlsHidden.value) {
        clearTimeout(inactivityTimer.value);
        inactivityTimer.value = setTimeout(() => {
            // 隐藏控制栏
            isControlsHidden.value = true;
        }, 5000);
    }
}
const togglePlayPause = () => {
    if (videoRef.value) {
        if (videoRef.value.paused) {
            videoRef.value.play().catch(error => {
                ElMessage.error('播放失败，请检查网络连接。');
            });
        } else {
            videoRef.value.pause();
        }
        isPlaying.value = !videoRef.value.paused;
    }
};

const refreshVideo = () => {
    // 设置旋转状态为true
    isRefreshing.value = true;
    // 假设刷新视频的逻辑是一个异步操作，完成后重置旋转状态为false
    setTimeout(() => {
        isRefreshing.value = false;
    }, 1000);
    if (hls) {
        hls.destroy();
        hls = null;
    }
    if (videoRef.value) {
        videoRef.value.src = '';
        videoRef.value.load();
        // 重新加载视频
        isPlaying.value = false;
        playVideo();
    }
};
//定义节流函数
const showNetworkErrorInfo = throttle(() => {
    ElMessage.info('网络连接中断，正在尝试重新连接...');
}, 5000, { leading: true, trailing: false })
//限制每5秒显示一次信息，leading:节流开始前,[trailing=true] (boolean): 指定调用在节流结束后。
const showMediaErrorInfo = throttle(() => {
    ElMessage.error('媒体错误，无法播放。');
}, 5000, { leading: true, trailing: false }); // 限制每5秒显示一次信息
const showBufferStalledErrorInfo = throttle(() => {
    ElMessage.error('播放恢复失败,请检查网络连接。');
}, 5000, { leading: true, trailing: false }); // 限制每5秒显示一次信息
const playVideo = () => {
    if (videoRef.value && !isPlaying.value) {
        if (Hls.isSupported()) {
            hls = new Hls();
            hls.loadSource(currentSrc.value);
            hls.attachMedia(videoRef.value);
            // 监听加载源失败事件
            hls.on(Hls.Events.ERROR, function (event, data) {
                if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
                    showNetworkErrorInfo(); // 使用节流函数
                } else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
                    showMediaErrorInfo(); // 使用节流函数
                    console.error('媒体错误：', data);
                    if (data.details === Hls.ErrorDetails.BUFFER_STALLED_ERROR) {
                        // 尝试自动恢复播放
                        videoRef.value.play().catch(error => {
                            showBufferStalledErrorInfo(); // 使用节流函数
                        })
                    }
                } else if (event === Hls.Events.MANIFEST_PARSED) {
                    // 监听清单解析完成事件
                    console.log('HLS manifest parsed, attempting to play...');
                    videoRef.value.play().catch(error => {
                        ElMessage.success('直播已开始，请等待主播开始直播~0.0');
                    });
                }
                else {
                    ElMessage.error('未知错误，加载源失败。');
                    console.error('未知错误：', data);
                }
            });
        } else if (videoRef.value.canPlayType('application/vnd.apple.mpegurl')) {
            videoRef.value.src = currentSrc.value;
            videoRef.value.addEventListener('loadedmetadata', function () {
                console.log('Loaded metadata, attempting to play...');
                videoRef.value.play().catch(error => {
                    ElMessage.error('播放失败，请检查网络连接。');
                });
            });
            // 监听加载源失败情况（对于原生支持 HLS 的浏览器）
            videoRef.value.addEventListener('error', function (event) {
                ElMessage.error('加载资源失败，请检查网络连接。');
            });
        } else {
            ElMessage.error('您的浏览器不支持播放 HLS 直播流，请更换浏览器或使用其他播放器。');
        }
        isPlaying.value = true;
    }
};

const handleVideoError = (event) => {
    console.error('视频加载失败:', event);
    ElMessage.error('视频加载失败，请检查网络连接。');
};

const sendMessage = () => {
    if (newMessage.value.trim() === '') return;
    emit('sendMessage', newMessage.value);
    newMessage.value = '';
    scrollToBottom();
};

const scrollToBottom = () => {
    const chatMessagesElement = document.querySelector('.chat-messages');
    if (chatMessagesElement) {
        chatMessagesElement.scrollTop = chatMessagesElement.scrollHeight;
    }
};

const changeQuality = () => {
    currentSrc.value = selectedQuality.value;
    refreshVideo();
};

onMounted(() => {
    playVideo();
    scrollToBottom();

    // 设置初始定时器
    inactivityTimer.value = setTimeout(() => {
        // 隐藏控制栏
        isControlsHidden.value = true;
    }, 5000)
});

onUnmounted(() => {
    if (hls) {
        hls.destroy();
        hls = null;
    }
    if (videoRef.value) {
        videoRef.value.pause();
    }
    // 清除定时器
    clearTimeout(inactivityTimer.value);
});

watch(() => props.chatMessages.length, () => {
    scrollToBottom();
});
</script>

<style scoped lang="scss">
.volume-container {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    flex-direction:column;
    bottom: 20px;
    right: 120px;
    /* 调整位置，避免与其他控件重叠 */
    font-size: 18px;
}

.iconfont.icon-24gf-volumeMiddle,
.iconfont.icon-24gf-volumeDisable {
    position: relative;
    bottom: -10px;
    right: 160px;
    /* 调整音量按钮的位置，避免与滑块重叠 */
    font-size: 27px;
    color: #27ba9b;
}

.volume-control {
    width: 100px;
    /* 适当调整音量条的宽度 */
    margin-top: 10px;
}

input[type="range"] {
    width: 100%;
    /* 填满父容器的宽度 */
    -webkit-appearance: none;
    appearance: none;
    background: #ddd;
    border-radius: 5px;
    height: 5px;
    margin: 0;
    /* 让音量条竖直显示 */
    transform: rotate(0deg);
}

input[type="range"]::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 20px;
    height: 20px;
    background: #27ba9b;
    border-radius: 50%;
    cursor: pointer;
}

input[type="range"]:focus {
    outline: none;
}


/* 定义旋转动画 */
@keyframes spin {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}

/* 定义刷新按钮的旋转效果类 */
.refresh-spin {
    animation-name: spin;
    animation-duration: 1s;
    animation-fill-mode: forwards;
}

.video-player {
    position: relative;
    width: 100%;
    height: 100%;
}

.live-video {
    width: 100%;
    height: 100%;
    object-fit: fill;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.custom-controls {
    display: flex;
    align-items: center;
    padding: 10px;
    border-radius: 8px;
    z-index: 100;
}

.iconfont {
    cursor: pointer;
    font-size: 30px;

    &.icon-zanting {
        position: absolute;
        bottom: 10px;
        left: 10px;
        font-size: 30px;
        color: #27ba9b;
    }

    &.icon-bofang {
        position: absolute;
        bottom: 10px;
        left: 10px;
        font-size: 30px;
        color: #27ba9b;
    }

    &.icon-shuaxin {
        position: absolute;
        bottom: 10px;
        left: 60px;
        font-size: 30px;
        color: #27ba9b;
    }

    &.icon-danmushezhi {
        position: absolute;
        bottom: 10px;
        left: 110px;
        font-size: 30px;
        color: #27ba9b;
    }

    &.icon-guanbidanmu {
        position: absolute;
        bottom: 10px;
        left: 110px;
        font-size: 30px;
        color: #27ba9b;
    }

    &.icon-quanping {
        position: absolute;
        bottom: 5px;
        right: 0px;
        font-size: 30px;
        color: #27ba9b;
    }

    /*打开音量*/
    &.icon-24gf-volumeMiddle {
        position: absolute;
        right: 120px;
        font-size: 27px;
        color: #27ba9b;
    }

    /*关闭音量 */
    &.icon-24gf-volumeDisable {
        position: absolute;
        right: 120px;
        font-size: 27px;
        color: #27ba9b;
    }
}

.refresh-video-btn {
    background-color: #fff;
    border: none;
    padding: 8px 12px;
    margin: 0 5px;
    cursor: pointer;
    border-radius: 4px;
    color: #333;
    font-size: 14px;
    position: absolute;
    bottom: 10px;
    left: 70px;
}

.quality-select {
    background-color: #fff;
    padding: 8px 12px;
    cursor: pointer;
    border-radius: 4px;
    color: #27ba9b;
    font-size: 12px;
    position: absolute;
    bottom: 10px;
    right: 40px;
}

.play-pause-btn:hover,
.refresh-video-btn:hover,
.quality-select:hover {
    background-color: #ddd;
}
</style>
